package com.example.demo.common;

import com.example.demo.common.constant.ResultCode;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel(value = "接口返回数据")
public class ResultData<T> {
    @ApiModelProperty("标识符：1成功，0警告，-1参数校验异常，-2身份验证异常，-3数据异常，-4业务逻辑异常, -8未定义异常，-9系统异常")
    public Integer code;

    @ApiModelProperty("异常种类代码")
    public Integer type;

    @ApiModelProperty("提示信息：正常时返回【成功】，警示时返回【WARN:XXX】，异常时返回【ERROR:XXX】")
    public String message;

    public T data;

    public static <T> ResultData<T> ok() {
        return ok(null);
    }

    public static <T> ResultData<T> ok(T data) {
        ResultData<T> res = new ResultData<>();
        res.init(1, ResultCode.SUCCESS, data);
        return res;
    }

    private void init(Integer code, ResultCode resultCode, T data) {
        this.code = code;
        this.type = resultCode.getCode();
        this.data = data;
        if (this.type == 1) {
            this.message = resultCode.getMessage();
        } else if (this.type == 0) {
            this.message = "WARN:" + resultCode.getMessage();
        } else {
            this.message = "ERROR:" + resultCode.getMessage();
        }
    }
}
